package com.exonline.controller.resource;

import cn.hutool.core.util.IdUtil;
import com.exonline.base.IBaseServlet;
import com.exonline.commons.utils.QiNiuUploadUtils;
import com.exonline.entity.CoursesResource;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/font/ResourceManagement")
public class ResourceServlet extends HttpServlet implements IBaseServlet {
    ObjectMapper mapper = new ObjectMapper();
    ResourceService service = new ResourceService();

    static QiNiuUploadUtils qiNiuUploadUtils = new QiNiuUploadUtils();

    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40;
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 1024 ;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        try {
            if ("query".equals(method)) {
                this.query(req, resp);
            } else if ("queryone".equals(method)) {
                this.queryOne(req, resp);
            } else if ("add".equals(method)) {
                this.add(req, resp);
            } else if ("edit".equals(method)) {
                this.edit(req, resp);
            } else if ("delete".equals(method)) {
                this.delete(req, resp);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    @Override
    public void query(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        int pageno = Integer.parseInt(req.getParameter("pageno"));
        List<CoursesResource> resourceManagements = service.queryAll(1, pageno);;
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", resourceManagements);
        mapper.writeValue(resp.getWriter(),map);
    }

    @Override
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String id = req.getParameter("id");
        service.deleteById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "删除成功");
        map.put("data", id);
        mapper.writeValue(resp.getWriter(), map);
    }

    @Override
    public void queryOne(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String id = req.getParameter("id");
        service.queryOneForId(id);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", id);
        mapper.writeValue(resp.getWriter(), map);
    }

    @Override
    public void edit(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String id = req.getParameter("id");
        String url = req.getParameter("url");
        service.update(id, url);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "添加成功");
        map.put("data", id);
        mapper.writeValue(resp.getWriter(), map);
    }

    @Override
    public void add(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String cid = req.getParameter("cid");

        // 获取多个视频的url列表
        List<String> urlList = doVideoUrl(req, resp);

        // 创建一个列表来存储每个视频的ID和URL
        List<Map<String, String>> videoDataList = new ArrayList<>();

        for (String url : urlList) {
            String id = IdUtil.simpleUUID();
            Map<String, String> videoData = new HashMap<>();
            videoData.put("id", id);
            videoData.put("cid", cid);
            videoData.put("url", url);

            // 将视频数据添加到列表中
            videoDataList.add(videoData);
            service.add(id,cid,url);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "添加成功");
        mapper.writeValue(resp.getWriter(), map);
        }
    public static List<String> doVideoUrl(HttpServletRequest request, HttpServletResponse response) throws  IOException {

        List<String> urlList = new ArrayList<>();

        {
            System.out.println(request.getParameter("id"));
            // 检测是否为多媒体上传
            if (!ServletFileUpload.isMultipartContent(request)) {
                // 如果不是则停止
                PrintWriter writer = response.getWriter();
                writer.println("Error: 表单必须包含 enctype=multipart/form-data");
                writer.flush();
                return urlList;
            }

            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            // 设置临时存储目录
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);

            // 设置最大文件上传值
            upload.setFileSizeMax(MAX_FILE_SIZE);

            // 设置最大请求值 (包含文件和表单数据)
            upload.setSizeMax(MAX_REQUEST_SIZE);

            // 中文处理
            upload.setHeaderEncoding("UTF-8");



            try {
                // 解析请求的内容提取文件数据
                @SuppressWarnings("unchecked")
                List<FileItem> formItems = upload.parseRequest(request);

                if (formItems!= null && formItems.size() > 0) {
                    // 迭代表单数据
                    for (FileItem item : formItems) {
                        // 处理不在表单中的字段
                        if (!item.isFormField()) {
                            // 上传文件到七牛云并获取返回的URL
                            String url = qiNiuUploadUtils.uploadFiles(item.getInputStream(), item.getName());

                            if (url!= null) {

                                urlList.add(url);

                                // 创建一个Map来存储要返回给前端的信息
                                Map<String, Object> resultMap = new HashMap<>();
                                resultMap.put("status", "success");
                                resultMap.put("message", "上传成功");
                                resultMap.put("url", url);


                                // 将Map转换为JSON格式并返回给前端
                                ObjectMapper mapper = new ObjectMapper();
                                mapper.writeValue(response.getWriter(), resultMap);
                            } else {
                                Map<String, Object> resultMap = new HashMap<>();
                                resultMap.put("status", "failure");
                                resultMap.put("message", "上传失败");

                                ObjectMapper mapper = new ObjectMapper();
                                mapper.writeValue(response.getWriter(), resultMap);
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                // 处理上传过程中出现的异常情况
                request.setAttribute("message", "错误信息: " + ex.getMessage());

                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("status", "failure");
                resultMap.put("message", "上传过程中出现错误");

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getWriter(), resultMap);
            }
        }
        return urlList;
    }
}
